package com.younion.action.manage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.younion.business.ICardEntityService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.SysConstants;
import com.younion.common.paginator.Paginator;
import com.younion.common.util.ImageFileUtil;
import com.younion.util.UUIDUtil;
import com.younion.vo.CardAgioVO;
import com.younion.vo.CardEntityVO;
import com.younion.vo.CardLevelVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author seagull
 */
public class CardEntityAction extends BaseAction {

    private static final long serialVersionUID = 1L;

    protected static final Log logger = LogFactory.getLog(CardEntityAction.class);

    private ICardEntityService cardEntityService = null;

    private CardEntityVO cardEntityVO = new CardEntityVO();

    private List<CardEntityVO> cardEntityList;// 结果集列表

    private String searchType;
    
    private List<CardLevelVO> cardLevelList = Lists.newArrayList();
    private List<CardAgioVO> cardAgioList = Lists.newArrayList();

    /**
     * 列表：翻页区；数据区
     */
    @SuppressWarnings("unchecked")
    @RequiresPermissions("listCardEntity")
    public String listCardEntity() {
        try {
            Map paramMap = null;
            if (getSessionUser().getCustomer() != null) {
                cardEntityVO.setCustomerId(getSessionUser().getCustomer().getId());
            }
            if (cardEntityVO != null) {
                if (cardEntityVO.getCardLever() != null && cardEntityVO.getCardLever() == -1) {
                    cardEntityVO.setCardLever(null);
                }
                paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(cardEntityVO));
            }
            // 获取总记录数
            int total = cardEntityService.getCountByMap(paramMap);
            // 根据总记录数获取分页对象
            Paginator paginator = this.getPaginator(total);
            cardEntityList = cardEntityService.get(paramMap, paginator);
            // 保存分页对象
            this.savaPaginator(paginator);
            this.addLog(2, "查询会员卡实体列表", "查询会员卡实体列表", this.getSessionUser());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return SUCCESS;
    }

    /**
     * 新增
     */
    @RequiresPermissions("addCardEntity")
    public String addCardEntity() {
        UUIDUtil uuidUtil = new UUIDUtil();
        cardEntityVO.setSchemeCode("YU" + uuidUtil.getUuid());
        return SUCCESS;
    }

    /**
     * 修改保存，调度Jsp
     */
    @RequiresPermissions("editCardEntity")
    public String editCardEntity() {
        try {
            cardEntityVO = cardEntityService.getById(cardEntityVO.getId().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
    
    public String viewCardEntity() {
    	try {
            cardEntityVO = cardEntityService.getById(cardEntityVO.getId().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 保存动作
     */
    @RequiresPermissions("saveCardEntity")
    public String saveCardEntity() {
        try {
            if (cardEntityVO.getCardIssueAmount() == null)
                cardEntityVO.setCardIssueAmount(0);
            int cardEntityKey = cardEntityService.saveReturnKey(cardEntityVO);
            ImageFileUtil.processImageFiles(cardEntityKey, "1,2", request);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        } finally {
            request.setAttribute("refreshNavTabId", "cardEntityList");
        }
        String id = cardEntityVO.getId() == null ? "" : cardEntityVO.getId().toString();
        String log = "".equals(id) ? "添加会员卡实体" : "更新会员卡实体";
        int type = "".equals(id) ? 3 : 4;
        this.addLog(type, log + id, log, getSessionUser());
        return SUCCESS;
    }

    /**
     * 删除
     */
    @RequiresPermissions("deleteCardEntity")
    public String deleteCardEntity() {
        try {
            String realPath = request.getSession().getServletContext().getRealPath(SysConstants.CARD_IMG_PATH);
            String pkId = request.getParameter("ids");
            List<String> list = new ArrayList<String>();
            Map<String, Integer> map = new HashMap<String, Integer>();
            String[] arr = pkId.split(",");
            for (String id : arr) {
                map.put("cardId", Integer.valueOf(id));
                int count = memberCardService.getCountByMap(map);
                if (count == 0) {
                    list.add(id);
                    File directory = new File(realPath + File.separator + id);
                    CardEntityVO cardvo = cardEntityService.getById(id);
                    String fileNames = cardvo.getNonactivatedPic() + "," + cardvo.getActivatedPic();
                    ImageFileUtil.deleteImage(directory, fileNames, true);
                }
                map.clear();
            }
            cardEntityService.remove(list);
            request.setAttribute("refreshNavTabId", "cardEntityList");
            String log = "删除会员卡实体";
            this.addLog(5, log + pkId, log, getSessionUser());
            tipMessage = "成功删除" + list.size() + "条记录，有" + (arr.length - list.size()) + "条记录因为已经被实例化而无法删除";
            request.setAttribute("tipMessage", tipMessage);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查看图片
     * 
     * @return
     * @throws IOException
     */
    public void viewImage() throws IOException {
        String id = request.getParameter("id");
        String picname = request.getParameter("picname");
        String realPath = request.getSession().getServletContext().getRealPath(SysConstants.CARD_IMG_PATH);
        System.out.println("realPath:" + realPath);
        if (StringUtils.isNotEmpty(picname) && StringUtils.isNotEmpty(id)) {
            File file = new File(realPath + File.separator + id, picname);
            if (file.exists()) {
                FileInputStream fIS = null;
                ServletOutputStream servletOut = null;
                try {
                    response.reset();
                    response.setContentType("image/jpeg");
                    response.setContentLength((int) file.length());
                    fIS = new FileInputStream(file);
                    servletOut = response.getOutputStream();
                    byte[] buf = new byte[1024];
                    int iRead = 0;
                    while (true) {
                        iRead = fIS.read(buf);
                        if (iRead > 0) {
                            servletOut.write(buf, 0, iRead);
                        } else
                            break;
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fIS.close();
                        servletOut.flush();
                        servletOut.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public CardEntityVO getCardEntityVO() {
        return cardEntityVO;
    }

    public void setCardEntityVO(CardEntityVO cardEntityVO) {
        this.cardEntityVO = cardEntityVO;
    }

    public void setCardEntityService(ICardEntityService cardEntityService) {
        this.cardEntityService = cardEntityService;
    }

    public List<CardEntityVO> getCardEntityList() {
        return cardEntityList;
    }

    public void setCardEntityList(List<CardEntityVO> cardEntityList) {
        this.cardEntityList = cardEntityList;
    }

    public String getSearchType() {
        return searchType;
    }

    public void setSearchType(String searchType) {
        this.searchType = searchType;
    }

    public List<CardLevelVO> getCardLevelList() {
        if(CollectionUtils.isEmpty(cardLevelList)){
            Integer customerId = getCustomerId();
            cardLevelList = memoryCacheManager.getCardLevel( customerId );
        }
        return cardLevelList;
    }

    private Integer getCustomerId() {
        Integer customerId = -1;
        if(cardEntityVO.getCustomerId() != null){
            customerId = cardEntityVO.getCustomerId();
        }else if (getSessionUser().getCustomer() != null){
            customerId = getSessionUser().getCustomer().getId();
        }
        return customerId;
    }

    public void setCardLevelList(List<CardLevelVO> cardLevelList) {
        this.cardLevelList = cardLevelList;
    }

    public List<CardAgioVO> getCardAgioList() {
        if(CollectionUtils.isEmpty(cardAgioList)){
            Integer customerId = getCustomerId();
            cardAgioList = memoryCacheManager.getCardAgio( customerId );
        }
        return cardAgioList;
    }

    public void setCardAgioList(List<CardAgioVO> cardAgioList) {
        this.cardAgioList = cardAgioList;
    }
    
    
}